<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/7
 * Time: 1:51
 */
namespace App\Http\Controllers\Api\v1\User;

use App\Http\Controllers\Api\BaseController;
use App\Models\Api\User;
use App\Models\Api\Wechat;

use Illuminate\Support\Facades\Input;
use DB;
use Request;

/**
 * @title
 * @desc
 * @url
 * @version 1.3.0
 * Class Bind
 * @package app\api\controller\v2
 */
class BindController extends BaseController
{
    protected $restActionList = ['index','read','save','update','delete'];
    const ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    const GET_USERINFO_URL = 'https://api.weixin.qq.com/sns/userinfo';
    private $appid;
    private $appsecret;

    public function __construct()
    {
        parent::__construct();
        $this->appid = config('wechat.wechat_appid');
        $this->appsecret = config('wechat.wechat_appsecret');
    }

    /**
     * @title
     * @method post
     * @desc    绑定微信
     * @return array
     */
    public function bind_wechat()
    {
        if(!Request()->isMethod('post'))
        {
            return show(config('code.error'), '未知操作', [], 403 );
        }
        $code = Input::post('code','');

        // 判断是否有code参数(android)
        if(trim($code) == '')
        {
//            获取ios用户信息
            $user_info_json = Input::post('userinfo');
            if($user_info_json)
            {
                $user_info = json_decode($user_info_json,true);
                if(
                    !isset($user_info['nickname'])
                    || !isset($user_info['sex'])
                    || !isset($user_info['city'])
                    || !isset($user_info['province'])
                    || !isset($user_info['country'])
                    || !isset($user_info['headimgurl'])
                    || !isset($user_info['openid'])
                    || !isset($user_info['unionid'])
                ) return show(config('code.error'),'用户信息错误');
            }
            else
            {
                return show(config('code.error'),'用户信息错误');
            }
            $access_token = [
                'access_token'=>'',
                'refresh_token'=>'',
                'expires_in'=>0,
                'scope'=>'',
            ];
        }
        else
        {
            // 获取android用户信息
            $access_token_url = self::ACCESS_TOKEN_URL . "?appid=$this->appid&secret=$this->appsecret&code=$code&grant_type=authorization_code";
            $access_token = json_decode($this->curl_get($access_token_url),true);
            if(isset($access_token['errcode'])) return show(config('code.error'), $access_token['errcode'].$access_token['errmsg'], [], 403 );
            $userinfo_url = self::GET_USERINFO_URL . "?access_token=$access_token[access_token]&openid=$access_token[openid]&lang=zh_CN";
            $user_info = json_decode($this->curl_get($userinfo_url),true);
        }

        if(isset($user_info['errcode'])) return show(config('code.error'), $user_info['errmsg']);

        // 判断是否已经注册微信
        $user = Wechat::from('wechat as w')
            ->join('user as u','u.id','=','w.uid','INNER')
            ->where(['unionid'=>$user_info['unionid']])
            ->first(['u.id','w.nickname','u.avatar','u.forbidden','u.email','u.is_first_login','u.uc_id','u.sex','u.has_self_recode']);

        $time = time();
//        未注册微信
        if(empty($user))
        {
            //用户表绑定微信名称
            User::where(['id'=>$request->uid])->update(['nickname' =>$user_info['nickname']]);
            // 将微信信息存入微信表
            $wechat = [
                'uid'=>$request->uid,
                'nickname'=>$user_info['nickname'],
                'sex'=>$user_info['sex'],
                'city'=>$user_info['city'],
                'province'=>$user_info['province'],
                'country'=>$user_info['country'],
                'headimgurl'=>$user_info['headimgurl'],
                'openid'=>$user_info['openid'],
                'unionid'=>$user_info['unionid'],
                'create_time'=>$time,
                'update_time'=>$time,
                'access_token'=>$access_token['access_token'],
                'refresh_token'=>$access_token['refresh_token'],
                'expires_in'=>$access_token['expires_in'] + $time,
                'scope'=>$access_token['scope'],
            ];

            Wechat::insertGetId($wechat);// 微信账号记录
            $nickname['nickname'] =$user_info['nickname'];

            return show(200, '绑定成功','');
        }
        return show(config('code.error'), '该微信已被其他账号绑定');
    }

    /**
     * 发起GET请求
     * @param string $url
     * @return mixed
     */
    protected function curl_get($url='')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    /**
     * @title  解绑微信
     * @method DELETE
     * @desc
     * @return array
     */
    public function unbind_wechat()
    {
        if(!Request()->isMethod('delete'))
        {
            return show(config('code.error'), '未知操作', [], 403 );
        }
        try
        {
            $tel = User::where('id',$request->uid)->first(['tel'])->toArray();
            if (isset($tel['tel']) && $tel){
                User::where('id',$request->uid)->update(['nickname'=>'']);
                Wechat::where('uid',$request->uid)->delete();
            }else{
                return show(config('code.error'),'您未绑定手机,不能解绑微信',[],401);
            }

        }catch(\Exception $e){
            return show(config('code.error'),$e->getMessage(),[],500);
        }
        return show(200,'解绑成功');
    }
}
